<!-- 添加文章 -->
<template>
    <a-page-header class="site-page-header">
        <template #tags>
            <a-popconfirm title="你确定要退出吗？ 未保存的内容会丢失" ok-text="是" cancel-text="不" @confirm="confirm" @cancel="cancel">
                <a-tag color="blue">x</a-tag>
            </a-popconfirm>
            <input class="tit_ipt" type="text" v-model="titletval">
        </template>
        <template #extra>
            <a-button key="1" type="primary" @click="okok">发布</a-button>
            <a-dropdown key="more">
                <a-button>
                    <menu-fold-outlined />
                </a-button>
                <template #overlay>
                    <a-menu>
                        <a-menu-item>
                            <a-button disabled>查看</a-button>
                            <!-- <a :href="'https://creationapi.shbwyz.com/' + route.params.id" target="blank">查看</a> -->
                        </a-menu-item>
                        <a-menu-item @click="showDrawer">
                            设置
                        </a-menu-item>
                        <a-menu-item @click="adddraft">
                            保存草稿
                        </a-menu-item>
                        <a-menu-item>
                            <a-button disabled>删除</a-button>
                        </a-menu-item>
                    </a-menu>
                </template>
            </a-dropdown>
        </template>
    </a-page-header>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 100vh; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="handleCreated" />
    </div>

    <!-- 抽屉 -->
    <!-- 抽屉 -->
    <a-drawer v-model:visible="visible" class="custom-class" title="文章设置" placement="right" width="600"
        @after-visible-change="afterVisibleChange">
        <a-card style="width: 100%">
            <a-form name="customized_form_controls" layout="inline" style="margin: 30px 0; background: #fff"
                expandFixed="true">
                <!-- 文件名称输入框 -->
                <div class="form_item">
                    <a-form-item name="price" label="文章摘要">
                        <a-input v-model:value="summary" placeholder="请输入内容" />
                    </a-form-item>
                </div>
                <!-- 文件名称输入框 -->
                <div class="form_item">
                    <a-form-item name="price_1" label="文章顺序">
                        <a-input v-model:value="order" placeholder="请输入内容" />
                    </a-form-item>
                </div>
                <!-- 封面 -->
                <div class="form_item">
                    <a-form-item label="封面">
                        <a-upload-dragger v-model:fileList="fileList" name="file" :multiple="true"
                            @change="handleChangefile" @drop="handleDrop" :customRequest="setfile" :showUploadList="false">
                            <div v-if="cover == ''">
                                <p class="ant-upload-text">点击选择文件或将文件拖拽到此处</p>
                                <p class="ant-upload-hint">文件将上传到OSS,如未配置请先配置</p>
                            </div>
                            <img v-else :src="cover" class="imgsa" alt="">
                        </a-upload-dragger>

                        <a-input v-model:value="cover" placeholder="请输入名称" />
                    </a-form-item>
                </div>
                <!-- 按钮 -->
                <div class="form_item">
                    <a-form-item>
                        <a-space>
                            <a-button @click="() => showDrawers()">选择文件</a-button>
                            <a-button @click="yichu">移除</a-button>
                        </a-space>
                    </a-form-item>
                </div>
                <a-form-item expandFixed="right">
                    <a-button type="primary" @click="asy">确认</a-button>
                </a-form-item>
            </a-form>
        </a-card>
    </a-drawer>
    <!-- 抽屉2.0 -->
    <a-drawer v-model:visible="visibles" class="custom-class" title="文件选择" placement="right" width="800"
        @after-visible-change="afterVisibleChanges">
        <a-card style="width: 100%">
            <!-- 搜索 -->
            <a-form name="customized_form_controls" layout="inline" :model="file_values" @finish="onFinishe"
                style="margin: 30px 0; background: #fff" expandFixed="true">
                <!-- 文件名称输入框 -->
                <a-form-item name="price" label="文件名称">
                    <a-input v-model:value="file_values.title" placeholder="请输入标题" />
                </a-form-item>
                <!-- 文件类型输入框 -->
                <a-form-item name="price" label="文件类型">
                    <a-input v-model:value="file_values.types" placeholder="请输入标题" />
                </a-form-item>
                <a-form-item expandFixed="right">
                    <a-button type="primary" html-type="submit">搜索</a-button>
                    <a-button @click="() => toset()">重置</a-button>
                </a-form-item>
            </a-form>
        </a-card>
        <br />
        <a-card style="width: 100%">
            <div class="imgs_box">
                <div v-for="(item, ind) in fileLists" :key="ind" @click="() => editurl(item.url)">
                    <img :src="item.url" alt="">
                    <p style="font-weight: bold;">{{ item.originalname }}</p>
                    <p style="font-size: 12px;">上传于：{{ item.createAt }}</p>
                </div>
            </div>
        </a-card>
        <a-card style="width: 100%">
            <a-pagination v-model:current="file_current" v-model:page-size="file_pageSize" :total="totals"
                :page-size-options="pageSizeOptionse" show-size-changer @showSizeChange="onShowSizeChangee"
                @change="pageChagee" />
        </a-card>

    </a-drawer>
</template>

<script setup lang="ts">
import { MenuFoldOutlined, CloseOutlined } from '@ant-design/icons-vue';
import { ref, reactive, onBeforeUnmount, shallowRef, onMounted, watch, onUpdated } from "vue"
import { useRoute, useRouter } from "vue-router"
// import { useHome } from "../../store/home";
import { usePage } from "../../store/page"
import { useFiles } from "../../store/files"
import { storeToRefs } from "pinia"
//编辑器
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IDomEditor } from '@wangeditor/editor'
import { message } from 'ant-design-vue';
let route = useRoute()
let router = useRouter()
//初始化pinia
// let homes = useHome()
let pages = usePage()
let ufiles = useFiles()
pages.getsearchpages({ page: 1, pageSize: 100 })

let { cover, fileLists, totals } = storeToRefs(ufiles)
let { isaddpage, pageList } = storeToRefs(pages)

let titletval = ref("");
let toc = ref("");
//访问路径
let summary = ref(""),
    order = ref(0),
    //发布状态
    status = ref("publish");


//定义搜索框的初始数据
const file_values = reactive({
    title: "",
    types: ""
});
//重置
const toset = () => {
    location.reload()
}
const editurl = (val: any) => {
    cover.value = val
    visibles.value = false;
}
//上传
const setfile = (v: any) => {
    // console.log(v, "set file")
}
let fileList = ref([]),
    handleDrop = (e: DragEvent) => {
        console.log(e);
    };
const showDrawers = () => {
    visibles.value = true;
    //初始化页面数据
    localStorage.removeItem("searchobj")
};
const afterVisibleChanges = (bool: boolean) => {
    console.log('visible', bool);
};


//上传
const handleChangefile = async (info: any) => {
    console.log(info.file.originFileObj, "info")
    ufiles.uploadfile(info.file.originFileObj)

};
// 移除
const yichu = () => {
    cover.value = ""
}

const confirm = (e: MouseEvent) => {
    console.log(e);
    //   message.success('Click on Yes');
    router.push("/")
};

const cancel = (e: MouseEvent) => {
    console.log(e);
    message.error('Click on No');
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
let mode = 'default';
// 内容 HTML
let valueHtml = ref('')
let textVal = ref("");
let editor = null as any;

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

onMounted(() => {
    editor = editorRef.value
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor: any) => {// `content` 即为 JSON 内容
    const html = editor.getHtml()
    const text = editor.getText()
    editorRef.value = editor // 记录 editor 实例，重要！
}

//监听编辑器内容的改变
watch(valueHtml, (newval) => {
    let text = editorRef.value.getText()
    textVal.value = text
    let arr = [] as any;
    // console.log(editorRef.value, "values")
    if (editorRef.value) {
        editorRef.value.children.map((v: any) => {
            arr.push(v.children[0])
        })
        // console.log(JSON.stringify(arr), "toc")
        toc.value = JSON.stringify(arr)
    }
})
let item = {} as any;
let ids = "";
item = pageList.value.find((v: any) => v.id == route.params.id)

watch(pageList, (newval) => {
    item = [...newval].find((v: any) => v.id === route.params.id)
    console.log(item, "item  new")
    cover.value = item.cover || ""
    summary.value = item.path || ""
    titletval.value = item.name || ""
    status.value = item.status || "publish"
    textVal.value = item.content || ""
    toc.value = item.toc || ""
    valueHtml.value = item.html || ""
    ids = item.id || ""
    order.value = item.order || 0
})




//抽屉
const visible = ref<boolean>(false);
const visibles = ref<boolean>(false);

//开启抽屉
const showDrawer = () => {
    visible.value = true;
};
const afterVisibleChange = (bool: boolean) => {
    console.log('visible', bool);
};

//标签
const handleChange2 = (val: any) => {
    console.log(val, "标签")
}
//点击确定
const asy = () => {
    visible.value = false
}


let file_current = ref(1);
let file_pageSize = ref(8);
const pageSizeOptionse = ref<string[]>(['8', '12', '16', '20', '24']);

let file_flag = false;
//文件数据
let fileitem = {}
//初始化获取数据
ufiles.getsearchfiles({ page: file_current.value, pageSize: file_pageSize.value })
//切换分页条数
const onShowSizeChangee = (currents: number, pageSizes: number) => {
    console.log(currents, pageSizes, "页码，条数");
    file_current.value = 1
    file_pageSize.value = pageSizes;
};
//切换页数
const pageChagee = (page: number, pageSize: number) => {
    file_current.value = page;
    file_flag = false;
    searche()
}

//点击搜索获取表单数据
const onFinishe = () => {
    //点击模糊搜索
    console.log(file_values, "values")
    file_flag = true;
    searche()
}

//封装一个模糊搜索的方法
const searche = () => {
    let obj = {};
    if (file_flag) {
        file_current.value = 1,
            file_pageSize.value = 12
        obj = {
            page: file_current.value,
            pageSize: file_pageSize.value
        }
    } else {
        obj = JSON.parse(localStorage.getItem("searchobj") || "{}")
        obj = {
            ...obj,
            page: file_current.value,
            pageSize: file_pageSize.value
        }
    }
    if (file_values.title != "") {
        obj = { ...obj, originalname: file_values.title }
    }
    if (file_values.types != "") {
        obj = { ...obj, type: file_values.types }
    }

    ufiles.getsearchfiles(obj)
}
//点击发布
const okok = () => {

    let objs = {};
    objs = {
        ...item,
        ...objs,
        //标题
        name: titletval.value || "",
        //html
        html: valueHtml.value || "",
        //toc
        toc: toc.value || "",
        //content
        content: textVal.value || "",
        //路径
        path: summary.value || "",
        status: status.value || "publish",
        cover: cover.value || "",
        publishAt: new Date().toLocaleString(),
        views: 1245,
        updateAt: new Date().toLocaleString(),
        id: ids || "",
        order:order.value || 0
    }
    // homes.addtexts(objs)
    // console.log(objs, "objs")
    console.log(ids,"id")
    pages.editpages(ids,objs)
}
//点击保存草稿
const adddraft = () => {
    status.value = "draft"
    let objs = {};
    objs = {
        ...item,
        ...objs,
        //标题
        name: titletval.value || "",
        //html
        html: valueHtml.value || "",
        //toc
        toc: toc.value || "",
        //content
        content: textVal.value || "",
        //路径
        path: summary.value || "",
        status: status.value || "draft",
        cover: cover.value || "",
        order:order.value || 0,
        publishAt: new Date().toLocaleString(),
        views: 1245,
        updateAt: new Date().toLocaleString(),
        id: ids || ""
    }
    // homes.addtexts(objs)
    // console.log(objs, "objs")
    pages.editpages(ids,objs)
}

watch(isaddpage, (newval) => {
    if (newval !== "") {
        router.push("/editpage/" + newval)
    }
})

</script>

<style lang="scss">
.tit_ipt {
    border-left: none;
    border-top: none;
    border-right: none;
    background: none;
    outline: none;

    &:hover {
        border-bottom: 1px solid skyblue;
    }
}
</style>